/*-------------------------------------------------------------------------
   Copyright (C) 2010 One Laptop per Child

   This program is free software; you can redistribute it and/or modify it
   under the terms of the GNU General Public License as published by the
   Free Software Foundation; either version 2, or (at your option) any
   later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

   In other words, you are welcome to use, share and improve this program.
   You are forbidden to forbid anyone else to use, share and improve
   what you give them.   Help stamp out software-hoarding!

   As a special exception, you may use this file as part of a free software
   library for the XO of the One Laptop per Child project without restriction.
   Specifically, if other files instantiate
   templates or use macros or inline functions from this file, or you compile
   this file and link it with other files to produce an executable, this
   file does not by itself cause the resulting executable to be covered by
   the GNU General Public License.  This exception does not however
   invalidate any other reasons why the executable file might be covered by
   the GNU General Public License.
-------------------------------------------------------------------------*/

#include "cc_compat.h"
#include "chip.h"
#include "adc.h"
#include "uart.h"
#include "timer.h"

void adc_init(void)
{
	// A/D interrupts have to be enabled in order to get a done flag
	// (interestingly, since we never clear the conversion-done flag, we
	// probably don't even take subsequent interrupts.)
	ADDAEN |= 0x37;
	P3IE7 = 1;
	CLKCFG2 = 0x1f; // power-on default value
}

void adc_deinit(void)
{
	P3IE7 = 0;
	ADDAEN &= ~0x37;
	ADCTRL &= ~0x01;
	CLKCFG2 = 0x3; // Quanta fix for A/D subsystem not stopping properly
}

// We don't do anything in the ADC interrupt.
void intsrv_adc(void) interrupt 31
{
#ifdef LJMP_WORKAROUND
	_nop_(); _nop_(); _nop_(); _nop_(); _nop_();
#endif
}

// A/D on the IO3731 but some clients only want 8-bit
unsigned char read_ad_ch_8(unsigned char channel)
{
	ADCTRL = channel << 2;
	usec_delay(50);		// TODO: Get the real mux settle time

	ADCTRL |= 0x01;

	// A conversion takes 256us
	usec_delay(256);

	return ADCDAT1;
}

unsigned int read_ad_ch(unsigned char channel)
{
	(void)read_ad_ch_8(channel);

	return ((uint)ADCDAT1<<4)|ADCDAT0>>4;
}

